//
//  HeadBouncesView.m
//  HeadTabView
//
//  Created by 吴浪 on 15/12/23.
//  Copyright © 2015年 吴浪. All rights reserved.
//

#import "HeadBouncesView.h"
#import "Masonry.h"
#import "UIView+Frame.h"

@interface HeadBouncesView ()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, assign) CGFloat fistHeight; /**< 记录初始高度 */
@end
@implementation HeadBouncesView

- (instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)imageName scrollView:(UIScrollView *)scrollView {
    if (self = [super initWithFrame:frame]) {
        self.imageName = imageName;
        self.scrollView = scrollView;
        self.fistHeight = frame.size.height;
        [self addUI];
    }
    return self;

}

+ (instancetype)headBouncesViewWithFrame:(CGRect)frame imageName:(NSString *)imageName scrollView:(UIScrollView *)scrollView {
    return [[self alloc] initWithFrame:frame imageName:imageName scrollView:scrollView];
}


- (void)addUI {
    [self addSubview:self.imageView];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    self.scrollView.contentInset = UIEdgeInsetsMake(self.height, 0, 0, 0);
    [self.scrollView addSubview:self];
}

- (UIImageView *)imageView {
    if (_imageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        _imageView = imageView;
    }
    return _imageView;
}

- (void)setImageName:(NSString *)imageName {
    _imageName = [imageName copy];
    UIImage *image;
    if (_imageName.length > 0) {
        image = [UIImage imageNamed:_imageName];
    }else {
        image = nil;
    }
    self.imageView.image = image;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    id new = change[@"new"];
    if (object == self.scrollView && [keyPath isEqualToString:@"contentOffset"]) {
        CGPoint newOffset = [new CGPointValue];
        CGFloat y = newOffset.y;
        if (y < -self.fistHeight) {
            self.y = y;
            self.height = -y;
        }
    }
}

- (void)dealloc {
    [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
}
@end
